'use strict';

/**
 * @name 其他通用组件
 * @description 打开模态框组件
 * @author ZYF
 */
angular.module('metalabOperationApp').factory('MetaUtils', ['$state', '$rootScope', '$uibModal', 'MetaConstants', 'MetaFilter', 'MetaSearch', 'MetaSort', 'MetaResources', 'Passport', 'MetaRemind', function($state, $rootScope, $uibModal, MetaConstants, MetaFilter, MetaSearch, MetaSort, MetaResources, Passport, MetaRemind) {
    var metaUtils = {};

    metaUtils.initAppFunc = function() {
        $rootScope.tagOptions = [];
        $rootScope.originOptions = [];
        $rootScope.areasOptions = [];
        $rootScope.leaderCandidate = '暂无';
        $rootScope.leaderCandidateId = '';
        $rootScope.referenceCandidate = '暂无';
        $rootScope.referenceCandidateId = '';
        $rootScope.managerOptions = [];
        $rootScope.managerIdOptions = [];
        $rootScope.metaConstants = MetaConstants;
        MetaResources.technology.origins({}, function(data) {
            $rootScope.originOptions = data;
        }, function(error) {
            if (error.data.message === "登录信息已失效，请重新登录") {
                Passport.signOut();
                $state.go('meta.visitor');
            } else {
                MetaRemind.serverError(error);
            }
        });
        MetaResources.technology.queryAreas({}, function(data) {
            angular.forEach(data, function(value, key) {
                if (key !== '$promise' && key !== '$resolved') {
                    for (var i = 0; i < value.length; i++) {
                        var temp = {};
                        temp.firstArea = key;
                        temp.secondArea = value[i];
                        temp.areaValue = key + ":" + value[i];
                        $rootScope.areasOptions[$rootScope.areasOptions.length] = temp;
                    };
                    var other = {};
                    other.firstArea = key;
                    other.secondArea = '其他';
                    other.areaValue = key + ":" + value[i];
                    $rootScope.areasOptions[$rootScope.areasOptions.length] = other;
                }
            });
        }, function(error) {
            if (error.data.message === "登录信息已失效，请重新登录") {
                Passport.signOut();
                $state.go('meta.visitor');
            } else {
                MetaRemind.serverError(error);
            }
        });
        MetaResources.tags.technologies({}, function(data) {
            $rootScope.tagOptions = data;
        }, function(error) {
            if (error.data.message === "登录信息已失效，请重新登录") {
                Passport.signOut();
                $state.go('meta.visitor');
            } else {
                MetaRemind.serverError(error);
            }
        });
        $rootScope.signOut = function() {
            Passport.signOut();
        };

        //在开始转变状态时
        $rootScope.$on('$stateChangeStart', function(event, toState) {
            /**
             * 做页面权限认证,未登录跳转至登录页面
             */
            if (toState.name.indexOf('permission') !== -1) {
                if (!Passport.isSignIn()) {
                    event.preventDefault();
                    $rootScope.$broadcast('signOut');
                } else {
                    MetaResources.user.query({
                            'role': 'admin'
                        },
                        function(data) {
                            if ($rootScope.managerOptions.length === 0) {
                                for (var i = 0; i < data.length; i++) {
                                    $rootScope.managerOptions[$rootScope.managerOptions.length] = data[i].name;
                                    $rootScope.managerIdOptions[$rootScope.managerIdOptions.length] = data[i].id;
                                }
                            }
                        },
                        function(error) {
                            if (error.data.message === "登录信息已失效，请重新登录") {
                                Passport.signOut();
                                $state.go('meta.visitor');
                            } else {
                                MetaRemind.serverError(error);
                            }
                        });
                }
            } else {
                if (Passport.isSignIn()) {
                    event.preventDefault();
                    MetaResources.user.query({
                            'role': 'admin'
                        },
                        function(data) {
                            if ($rootScope.managerOptions.length === 0) {
                                for (var i = 0; i < data.length; i++) {
                                    $rootScope.managerOptions[$rootScope.managerOptions.length] = data[i].name;
                                    $rootScope.managerIdOptions[$rootScope.managerIdOptions.length] = data[i].id;
                                }
                            }
                            $state.go('meta.permission.message');
                        },
                        function(error) {
                            if (error.data.message === "登录信息已失效，请重新登录") {
                                Passport.signOut();
                                $state.go('meta.visitor');
                            } else {
                                MetaRemind.serverError(error);
                            }
                        });
                }
            }
        });
    };

    metaUtils.initListCtrl = function(scope, stateParams) {
        //初始化筛选模块
        MetaFilter.initFilterModule(scope.listCtrl.filterParams, scope.listCtrl.filterConfig, stateParams);
        //初始化搜索
        MetaSearch.initSearchModule(scope.listCtrl.searchParams, scope.listCtrl.searchConfig, stateParams, scope.changeUrl);
        //初始化排序，因为排序的字段只有一个，为了保证传饮用，所以需要传listCtrl对象
        MetaSort.initSortModule(scope.listCtrl, stateParams, scope.changeUrl);
        //初始化表格参数
        metaUtils.initTableModule(scope.listCtrl.tableParams, stateParams, scope.changeUrl);
        //初始化其他通用组件
        scope.openModel = metaUtils.openModel;
        //获取数据
        scope.getListData((stateParams.page !== undefined && parseInt(stateParams.page) > 0) ? stateParams.page : 1);
        //调整样式
        if (!angular.element(".meta-sidebar").hasClass('open-sidebar')) {
            angular.element(".meta-content").removeClass('open-sidebar');
        }
    };

    /**
     * @description 表格参数，data为数据，total为数据总数，currentPage为当前页数，pageNumber为每页条目的数量
     */
    metaUtils.initTableModule = function(tableParams, stateParams, changeUrl, isModal) {
        tableParams.data = [];
        tableParams.total = 0;
        tableParams.currentPage = 0;
        if (isModal) {
            tableParams.pageNumber = 5;
        } else {
            tableParams.pageNumber = 10;
        }
        if (stateParams) {
            tableParams.isShowAll = (stateParams.showAll === undefined ? false : (stateParams.showAll === 'true'));
            tableParams.showAllText = (tableParams.isShowAll ? "隐藏部分" : "显示所有");
            tableParams.showAll = function() {
                if (this.isShowAll) {
                    this.showAllText = "显示所有";
                } else {
                    this.showAllText = "隐藏部分";
                }
                this.isShowAll = !this.isShowAll;
                changeUrl();
            };
        }
        tableParams.jumpPages = function() {
            if (tableParams.jumpPage < 0) {
                MetaRemind.error("跳转失败", "跳转页不得小于0");
            } else if (tableParams.jumpPage > (tableParams.total / tableParams.pageNumber) + 1) {
                MetaRemind.error("跳转失败", "跳转页不得大于" + (parseInt(tableParams.total / tableParams.pageNumber) + 1));
            } else {
                tableParams.currentPage = tableParams.jumpPage;
                changeUrl();
            }
        }
        tableParams.jump = function(event) {
            if (event.keyCode === 13) {
                tableParams.jumpPages();
            }
        };
    };

    /**
     * @description 打开模态框：size设定模态框大小，templateUrl设定模版地址，controller设定使用的控制器，data定义传递的数据，flag定义一些判断字段，例如可以用来判断是创建还是编辑
     */
    metaUtils.openModel = function(size, templateUrl, controller, data, flag) {
        var modalInstance = $uibModal.open({
            animation: true,
            backdrop: 'static',
            templateUrl: templateUrl,
            controller: controller,
            size: size,
            resolve: {
                params: function() {
                    return {
                        flag: flag,
                        data: data
                    };
                }
            }
        });
    };

    /**
     * @description 返回range的范围
     */
    metaUtils.getRange = function(page, pageNumber) {
        return ((page - 1) * pageNumber + 1) + "_" + (page * pageNumber);
    };

    /**
     * @description 构建query参数
     */
    metaUtils.buildQueryParams = function(page, queryParams, dynamicQueryParams, listCtrl, stateParams) {
        //根据dynamicQueryParams，先把动态参数给确定了
        for (var i = 0; i < dynamicQueryParams.length; i++) {
            switch (dynamicQueryParams[i]) {
                case 'fund':
                    queryParams[MetaConstants.map.hasFund[parseInt(stateParams.fund)]] = MetaConstants.map.hasFund[parseInt(stateParams.fund) + (MetaConstants.map.hasFund.length / 2)];
                    break;
                case 'rank':
                    queryParams[MetaConstants.map.hasRank[parseInt(stateParams.rank)]] = MetaConstants.map.hasRank[parseInt(stateParams.rank) + (MetaConstants.map.hasRank.length / 2)];
                    break;
                case 'talent':
                    queryParams[MetaConstants.map.hasTalent[parseInt(stateParams.talent)]] = MetaConstants.map.hasTalent[parseInt(stateParams.talent) + (MetaConstants.map.hasTalent.length / 2)];
                    break;
                default:
                    break;
            }
        }
        //构建参数
        angular.forEach(queryParams, function(value, key) {
            switch (key) {
                case '_sort':
                    queryParams[key] = listCtrl.sortParams;
                    break;
                case '_range':
                    queryParams[key] = metaUtils.getRange(page, listCtrl.tableParams.pageNumber);
                    break;
                case 'areas':
                case 'partnerInfo.areas':
                    var result = '';
                    for (var i = 0; i < (MetaConstants.map.areas.length / 2); i++) {
                        result += (listCtrl.filterParams.area_choice[MetaConstants.map.areas[(MetaConstants.map.areas.length / 2) + i]] === true ? (MetaConstants.map.areas[i] + ',') : '');
                    }
                    queryParams[key] = (result === '' ? null : result.substring(0, result.length - 1));
                    break;
                case 'origin':
                    if (listCtrl.filterParams.origin.length !== 0) {
                        queryParams[key] = listCtrl.filterParams.origin.join();
                    } else {
                        queryParams[key] = null;
                    }
                    break;
                case 'projectManagerId':
                    var manager = (stateParams.manager === undefined ? [] : stateParams.manager.split(','));
                    var result = '';
                    for (var i = 0; i < manager.length; i++) {
                        result += ($rootScope.managerIdOptions[$rootScope.managerOptions.indexOf(manager[i])] + ',');
                    }
                    queryParams[key] = (result === '' ? null : result.substring(0, result.length - 1));
                    break;
                case 'disciplineClass':
                    if (listCtrl.filterParams.disciplineClass !== "所有学科" && listCtrl.filterParams.disciplineClass !== "") {
                        queryParams[key] = listCtrl.filterParams.disciplineClass;
                    } else {
                        queryParams[key] = null;
                    }
                    break;
                case 'discipline':
                    if (listCtrl.filterParams.discipline !== "所有学科" && listCtrl.filterParams.disciplineClass !== "") {
                        queryParams[key] = listCtrl.filterParams.discipline;
                    } else {
                        queryParams[key] = null;
                    }
                    break;
                case 'technologyForm':
                    if (listCtrl.filterParams.technologyForm !== "") {
                        queryParams[key] = listCtrl.filterParams.technologyForm;
                    } else {
                        queryParams[key] = null;
                    }
                    break;
                default:
            }
        });
        if (stateParams.type !== 'model') {
            if ($state.includes('meta.permission.demand')) {
                queryParams[($state.includes('meta.permission.demand.user') ? 'tags_not' : 'tags')] = '合作';
            } else if ($state.includes('meta.permission.technology')) {
                queryParams[($state.includes('meta.permission.technology.technology') ? 'tags_not' : 'tags')] = '合作';
            }
        }
        queryParams[stateParams.search] = stateParams.value;
    };

    /**
     * @description 接收列表函数
     */
    metaUtils.receiveListData = function(listCtrl, stateParams, page, data, header) {
        listCtrl.tableParams.data = data;
        listCtrl.tableParams.total = parseInt(header()['x-count']);
        listCtrl.tableParams.currentPage = page;
        listCtrl.tableParams.jumpPage = page;
        if (stateParams) {
            stateParams.page = page;
        }
    };

    return metaUtils;
}]);
